/**
 * Desc
 * @description Holp You Do Good But Not Evil
 * @copyright   Copyright 2014-2015 <ycchen@iwshop.cn>
 * @license     LGPL (http://www.gnu.org/licenses/lgpl.html)
 * @author      Chenyong Cai <ycchen@iwshop.cn>
 * @package     Wshop
 * @link        http://www.iwshop.cn
 */

// order id 生成标记
window.orderId = false;
// 支付完成标记
window.payed = false;
// 收货地址加载标记
window.addressloaded = false;
// 收货地址
window.expressData = {};
// lock
window.orderCreateLock = false;
// 初始运费
window.yunfeiInitial = 6.95;

require(['config'], function(config) {

    require(['util', 'jquery', 'Spinner', 'Cart', 'pdCounter'], function(util, $, Spinner, Cart, pdCounter) {

        var o = {};

        // localStorage对象
        o.Storage = window.localStorage;

        // 运费总额
        o.ExpFee = 0;

        // 运费起点
        o.ExpFeeInitial = 6.95;

        // 加载购物车数据
        o.loadCartData = function() {
            var jsonData = o.Storage.getItem('cart');
            if (typeof jsonData === 'undefined' || jsonData === '{}' || jsonData === null) {
                fnEmptyCartTip();
            } else {
                Spinner.spin($('#orderDetailsWrapper').get(0));
                $.post(shoproot + '?/vProduct/cartData/', {
                    data: jsonData.toString()
                }, function(Res) {
                    $('#orderDetailsWrapper').html(Res);
                    // 数量变化监听
                    fnPdCountChangerLis();
                    // 计算订单总额
                    $('#order_amount').html('&yen;' + countOrderAmount());
                    Spinner.stop();
                });
            }

            // 加载收货地址缓存数据
            localStorageAddrCache();

            // 余额支付点击监听
            $('#cart-balance-check').click(function() {
                if (parseFloat($('#cart-balance-pay').text()) > 0) {
                    $('#order_amount').html('&yen;' + countOrderAmount(this.checked));
                }
            });
        };

        // 加载购物车数据
        o.loadCartData();

        // 数量变化监听
        function fnPdCountChangerLis() {

            $('.productCountNumi').on('input', function() {
                //Cart.set($(this).attr('data-mhash'), $(this).val());
                $('#order_amount').html('&yen;' + countOrderAmount());
            });

            // 数量--
            $('.productCountMinus').bind({
                'touchend touchcancel mouseup': function(event) {
                    event.preventDefault();
                    var node = $(this).parent().find('.productCountNumi');
                    if (parseInt(node.val()) <= 1) {
                        delFromCart($(this).attr('data-pdid'), $(this).attr('data-spid'));
                    } else {
                        node.val(parseInt(node.val()) === 1 ? 1 : node.val() - 1);
                        Cart.set(node.attr('data-mhash'), node.val());
                    }
                    $('#order_amount').html('&yen;' + countOrderAmount());
                }
            });
            // 数量++
            $('.productCountPlus').bind({
                'touchend touchcancel mouseup': function(event) {
                    event.preventDefault();
                    var node = $(this).parent().find('.productCountNumi');
                    node.val(parseInt(node.val()) + 1);
                    Cart.set(node.attr('data-mhash'), node.val());
                    $('#order_amount').html('&yen;' + countOrderAmount());
                }
            });
        }

        /**
         * 删除订单商品
         * @param {type} productId
         * @param {type} spid
         * @returns {undefined}
         */
        function delFromCart(productId, spid) {
            Cart.del(productId, spid);
            $('#cartsec' + productId).remove();
            if (countOrderAmount() === 0) {
                fnEmptyCartTip();
                $('#order_amount').html('&yen;' + 0);
            } else {
                $('#order_amount').html('&yen;' + countOrderAmount());
            }
        }

        /**
         * localStorage 地址缓存
         * @returns {undefined}
         */
        function localStorageAddrCache() {
            if (o.Storage && o.Storage.getItem('addr-set') === "1" && o.Storage.getItem('orderAddress')) {
                expressData = JSON.parse(o.Storage.getItem('orderAddress'));
                if (expressData.proviceFirstStageName !== undefined) {
                    // 收货地址加载标记
                    window.addressloaded = true;
                    // 显示收货地址
                    addressShow();
                } else {
                    expressData = {};
                }
            }
        }

        /**
         * 原始数据测试
         * @returns {undefined}
         */
        function loadTestAddrData() {
            var res = {
                proviceFirstStageName: '新疆维吾尔自治区',
                addressCitySecondStageName: '广州市',
                addressCountiesThirdStageName: '天河区',
                addressDetailInfo: '新燕花园三期1201 新燕花园三期1201 新燕花园三期1201 新燕花园三期1201',
                addressPostalCode: 510006,
                telNumber: 18565518404,
                userName: '陈永才'
            };
            res.Address = res.proviceFirstStageName + res.addressCitySecondStageName + res.addressCountiesThirdStageName + res.addressDetailInfo;
            res.err_msg = 'edit_address:ok';
            addAddressCallback(res);
        }

        window.loadTestAddrData = loadTestAddrData;

        /**
         * 获取收货地址回调函数
         * @param {type} res
         * @returns {undefined}
         */
        function addAddressCallback(res) {
            if (res.err_msg === 'edit_address:ok') {
                window.expressData = res;
                expressData.Address = expressData.proviceFirstStageName + expressData.addressCitySecondStageName + expressData.addressCountiesThirdStageName + expressData.addressDetailInfo;
                res.Address = expressData.Address;
                // 缓存到Storage
                o.Storage.setItem('addr-set', '1');
                o.Storage.setItem('orderAddress', JSON.stringify(res));
                // 收货地址加载标记
                window.addressloaded = true;
                addressShow();
                // 地址变动 重新计算订单总额
                $('#order_amount').html('&yen;' + countOrderAmount());
            } else {
                $('#wrp-btn').html('授权失败');
            }
        }

        function addressShow() {
            $('#wrp-btn').remove();
            $('#express-name').html(expressData.userName);
            $('#express-person-phone').html(expressData.telNumber);
            $('#express-address').html(expressData.Address);
        }

        // 传出全局
        window.addAddressCallback = addAddressCallback;

        /**
         * 计算订单总额
         * @param {Boolean} balan_pay
         * @returns {Number}
         */
        function countOrderAmount(balan_pay) {
            // 余额支付
            balan_pay = balan_pay | false;

            /**
             * @param float ret 订单总金额
             * @param float tweight 订单商品总重量
             * @type Number|Number
             */
            var ret = 0, tweight = 0;

            if ($('.cartListDesc').length > 0) {
                $('.cartListDesc').each(function(lis, node) {
                    // 循环订单数据
                    var dprice = parseFloat($('.dprice', node).attr('data-price'));
                    var dcount = parseInt($('.dcount', node).val());
                    tweight += (parseInt($('.dprice', node).attr('data-weight')) * dcount);
                    ret += (dprice * dcount);
                });
            } else {
                return 0;
            }

            if (balan_pay) {
                ret -= parseFloat($('#cart-balance-pay').text());
                if (ret < 0)
                    ret = 0;
            }

            // 计算运费
            if (ret > 1 && addressloaded && tweight > 0) {
                var city = expressData.addressCitySecondStageName;
                var prov = expressData.proviceFirstStageName;
                if (prov.match(/广东/g)) {
                    o.ExpFeeInitial = 8;
                    if (city.match(/广州/g)) {
                        o.ExpFeeInitial = 10;
                    }
                }
                if (prov.match(/江苏|浙江|上海|安徽|广西|江西|福建|湖北|湖南|海南/g)) {
                    o.ExpFeeInitial = 11;
                }
                if (prov.match(/天津|北京|山东|河南|河北|重庆|云南|贵州|四川|陕西|山西/g)) {
                    o.ExpFeeInitial = 14;
                }
                if (prov.match(/辽宁|吉林|黑龙江/g)) {
                    o.ExpFeeInitial = 16;
                }
                if (prov.match(/青海|宁夏|新疆|西藏|甘肃|内蒙古/g)) {
                    o.ExpFeeInitial = 20;
                }
                if (tweight <= 1000) {
                    // 1公斤以下为ExpFeeInitial
                    o.ExpFee = o.ExpFeeInitial;
                } else {
                    // 1公斤以上每公斤增加邮费
                    if (expressData.proviceFirstStageName !== undefined) {
                        tweight -= 1000;
                        o.ExpFee = Math.ceil(tweight / 1000);
                        if (prov.match(/广东/g)) {
                            o.ExpFee *= 2;
                        }
                        if (prov.match(/江苏|浙江|上海|安徽|广西|江西|福建|湖北|湖南|海南/g)) {
                            o.ExpFee *= 6;
                        }
                        if (prov.match(/天津|北京|山东|河南|河北|重庆|云南|贵州|四川|陕西|山西/g)) {
                            o.ExpFee *= 8;
                        }
                        if (prov.match(/辽宁|吉林|黑龙江/g)) {
                            o.ExpFee *= 10;
                        }
                        if (prov.match(/青海|宁夏|新疆|西藏|甘肃|内蒙古/g)) {
                            o.ExpFee *= 15;
                        }
                        o.ExpFee += o.ExpFeeInitial;
                    } else {
                        o.ExpFee = o.ExpFeeInitial;
                    }
                }
            }

            o.ExpFee.toFixed(2);

            // 运费
            $('#order_yunfei').html('&yen;' + o.ExpFee.toFixed(2));
            // 总价
            $('#order_amount_sig').html('&yen;' + ret.toFixed(2));

            return (ret + o.ExpFee).toFixed(2);
        }

        // 购物车为空 提示
        function fnEmptyCartTip() {
            $('#order_yunfei').html('&yen;0');
            $('#order_amount_sig').html('&yen;0');
            $('#order_amount_sig').html('&yen;0');
            $('#orderDetailsWrapper').html('<div id="cartnothing" onclick="location=\'' + shoproot + '\'">购物车空空如也，去逛逛吧</div>');
        }

        /**
         * 获取收货地址
         * @returns {undefined}
         */
        function fnSelectAddr() {
            if ($('#addrOn').val() === '1') {
                WeixinJSBridge.invoke('editAddress', addrsignPackage, addAddressCallback);
            } else {
                fnPickAddress();
            }
        }

        util.fnTouchEnd('#express_address', fnSelectAddr);

        /**
         * 非微信接口获取收货地址
         * @todo opt
         * @returns {undefined}
         */
        function fnPickAddress() {
            $('#addrPick').load(shoproot + '?/Uc/selectOrderAddress/body=true', function() {
                $('.addrw').click(address_item_click);
                $('#addr-add-btn1').click(function() {
                    $('#addr-add').show();
                    $('#addr-select').hide();
                });
                $('#addr-add-btn-back').click(function() {
                    $('#addr-add').hide();
                    $('#addr-select').show();
                });
                $('#addr-add-btn').click(address_save);
                $('#addrPick').fadeIn();
            });
        }

        /**
         * 发起微信支付
         * @returns {undefined}
         */
        function wepayCall() {

            // 判断收货地址是否已经获取
            if (!addressloaded) {
                fnSelectAddr();
                return false;
            }

            if ($('#payOn').val() === '1') {
                // 微信支付开通
                if (false === window.addressloaded && typeof WeixinJSBridge !== "undefined") {
                    addAddress();
                    return false;
                }

                if (o.Storage.getItem('cart') === '{}' || !o.Storage.getItem('cart')) {
                    return false;
                }

                // cartData cache
                if (o.Storage.getItem('carthash') && CryptoJS.MD5(o.Storage.getItem('cart')).toString() === o.Storage.getItem('carthash').toString()) {
                    window.orderId = o.Storage.getItem('tmporder');
                } else {
                    o.Storage.removeItem('tmporder');
                    o.Storage.removeItem('carthash');
                    window.orderId = false;
                }

                $('#wechat-payment-btn').addClass('disable').html('支付发起中...');

                // 生成一个订单
                if (false === orderId) {
                    $.post($('#paycallorderurl').val(), {
                        addrData: expressData,
                        cartData: o.Storage.getItem('cart'),
                        balancePay: $('#cart-balance-check')[0].checked ? 1 : 0,
                        yun: o.ExpFee,
                        leword: ''
                    }, orderGenhandle);
                } else {
                    orderGenhandle(orderId);
                }
            } else {
                // 微信支付未开通，直接下单
                // 生成一个订单
                if (!window.orderCreateLock) {
                    window.orderCreateLock = true;
                    $.post($('#paycallorderurl').val(), {
                        addrData: expressData,
                        cartData: o.Storage.getItem('cart'),
                        balancePay: $('#cart-balance-check')[0].checked ? 1 : 0,
                        yun: o.ExpFee,
                        leword: $('#f-uname').val() + ' ' + $('#f-upid').val(),
                        uname: $('#f-uname').val(),
                        upid: $('#f-upid').val()
                    }, function(Id) {
                        window.orderCreateLock = false;
                        if (parseInt(Id) > 0) {
                            // success 
                            Cart.clear();
                            alert('下单成功！');
                            location.href = shoproot + '?/Uc/orderlist/';
                        } else {
                            alert('订单创建失败！');
                        }
                    });
                }
            }

            // 订单生成回调
            function orderGenhandle(Id) {
                orderId = parseInt(Id) > 0 ? parseInt(Id) : false;
                if (Id > 0 && false === window.payed) {
                    $.post(shoproot + "?/Order/ajaxGetBizPackage/", {
                        orderId: orderId
                    }, function(bizPackage) {
                        // 订单映射
                        o.Storage.setItem('carthash', CryptoJS.MD5(o.Storage.getItem('cart')));
                        o.Storage.setItem('tmporder', orderId);

                        bizPackage.success = wepayCallback;

                        // 发起微信支付
                        wx.chooseWXPay(bizPackage);
                    });
                }
            }
        }

        /**
         * 微信支付回调
         * @param {type} res
         * @returns {undefined}
         */
        function wepayCallback(res) {
            Cart.clear();
            window.payed = true;
            window.location.href = shoproot + '?/Uc/home';
            $('#wechat-payment-btn').removeClass('disable').html('微信安全支付');
        }

        $('#wechat-payment-btn').click(wepayCall);

        util.fnTouchEndRedirect('a', function(link) {
            location.href = link;
        });
    });

});